<?php

namespace app\admin\controller;

use app\admin\model\RoleModel;
use tools\MenuTools;
use think\Request;

class Role extends Base
{
    /**
     * 角色列表页面
     * @return \think\response\View
     */
    public function index()
    {
        return view('role/index');
    }

    /**
     * 角色列表
     * @param Request $request
     * @return \think\response\Json
     */
    public function lists(Request $request)
    {
        return RoleModel::lists($request->param());
    }

    /**
     * 角色创建页面
     * @return \think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function create()
    {
        $menus = json_encode(MenuTools::getMenu(), JSON_UNESCAPED_UNICODE);
        return view('role/create', compact('menus'));
    }

    /**
     * 角色创建
     * @param Request $request
     * @return \think\response\Json
     */
    public function createSubmit(Request $request)
    {
        $flag = $this->validate($request->param(), [
            'name' => 'require|length:2,20',
            'describe' => 'length:2,100',
            'status' => 'require|in:1,0',
            'menus' => 'require',
        ]);
        if ($flag !== true) {
            return baseResponse(1, $flag);
        }
        return RoleModel::createSubmit($request->param());
    }

    /**
     * 角色删除
     * @param int $id 角色ID
     * @return \think\response\Json
     */
    public function delete($id)
    {
        if (RoleModel::destroy($id)) {
            return baseResponse(0, '删除成功');
        }
        return baseResponse(1, '删除失败');
    }

    /**
     * 角色编辑页面
     * @return \think\response\View
     */
    public function update($id)
    {
        $role = RoleModel::find($id);
        $menus = json_encode(MenuTools::getMenu($id), JSON_UNESCAPED_UNICODE);
        return view('role/update', compact('role', 'menus'));
    }

    /**
     * 角色编辑页面
     * @param Request $request
     * @param int $id 角色ID
     * @return \think\response\Json
     */
    public function updateSubmit(Request $request, $id)
    {
        $flag = $this->validate($request->param(), [
            'name' => 'require|length:2,20',
            'describe' => 'length:2,100',
            'status' => 'require|in:1,0',
            'menus' => 'require',
        ]);
        if ($flag !== true) {
            return baseResponse(1, $flag);
        }
        return RoleModel::updateSubmit($request->param(), $id);
    }
}
